import { Interceptor } from './Interceptor';
import Logger from './Logger';
import systemDateTime from '@ohos.systemDateTime';
import { Utils } from './Utils';
import { Response } from './Response';

export class HttpLoggingInterceptor implements Interceptor {
  async intercept(chain: Interceptor.Chain): Promise<Response> {
    const request = chain.getRequest()

    const url = Utils.formatUrl(request.baseUrl, request.url, request.queryParams)
    let requestMessage = `--> ${request.httpMethod.method} ${url}`
    const headers = request.headers

    headers.forEach((v, k) => {
      requestMessage += "\n" + k + ": " + v
    })

    requestMessage += `\n--> END ${request.httpMethod.method}`


    const startNs = await systemDateTime.getRealTime(true)
    let response: Response
    try {
      response = await chain.proceed(request)
    } catch (e) {
      requestMessage += `\n<-- HTTP FAILED: ${e}`
      throw e
    }

    const endNs = await systemDateTime.getRealTime(true)
    const tookMs = (endNs - startNs) / 1000000

    Logger.d("HttpLoggingInterceptor", requestMessage)

    let responseMessage = `<-- ${response.code}${Utils.isEmpty(response.message) ? "" : ' ' + response.message} ${url} (${tookMs.toFixed()}ms)`


    const respHeaders = response.headers
    respHeaders.forEach((v, k) => {
      responseMessage += "\n" + k + ": " + v
    })

    Logger.d("HttpLoggingInterceptor", responseMessage)

    if (response.body) {
      Logger.d("HttpLoggingInterceptor", "")
      if (typeof response.body === "object") {
        responseMessage = `\nbody: ${JSON.stringify(response.body)}`
      } else {
        responseMessage = `\nbody: ${response.body}`
      }
    }

    Logger.d("HttpLoggingInterceptor", responseMessage)
    Logger.d("HttpLoggingInterceptor", "<-- END HTTP")

    return Promise.resolve(response)
  }
}